package utils

import (
	"bytes"
	"crypto/tls"
	"crypto/x509"
	"io/ioutil"
	"net/http"
	"strings"
	"github.com/tobyzxj/uuid"
	"crypto/md5"
	"fmt"
)

//ca证书的位置，需要绝对路径
var (
	wechatCertPath = `pem/apiclient_cert.pem`
	wechatKeyPath  = `pem/apiclient_key.pem`
	wechatCAPath   = `pem/rootca.pem`
)
var _tlsConfig *tls.Config

//采用单例模式初始化ca
func getTLSConfig() (*tls.Config, error) {
	if _tlsConfig != nil {
		return _tlsConfig, nil
	}
	// load cert
	cert, err := tls.LoadX509KeyPair(wechatCertPath, wechatKeyPath)
	if err != nil {
		return nil, err
	}
	// load root ca
	caData, err := ioutil.ReadFile(wechatCAPath)
	if err != nil {
		return nil, err
	}
	pool := x509.NewCertPool()
	pool.AppendCertsFromPEM(caData)
	_tlsConfig = &tls.Config{
		Certificates: []tls.Certificate{cert},
		RootCAs:      pool,
	}
	return _tlsConfig, nil
}

//携带ca证书的安全请求
func SecurePost(url string, xmlContent []byte) (*http.Response, error) {
	tlsConfig, err := getTLSConfig()
	if err != nil {
		return nil, err
	}
	tr := &http.Transport{TLSClientConfig: tlsConfig}
	client := &http.Client{Transport: tr}
	return client.Post(
		url,
		"application/xml",
		bytes.NewBuffer(xmlContent))
}

func GetRandomString() string {
	return strings.Replace(uuid.New(), "-", "", -1)
}

func Md5(data []byte) string {
	has := md5.Sum(data)
	md5str1 := fmt.Sprintf("%X", has) //将[]byte转成16进制
	return md5str1
}
